#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h> 
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
#define SERVPORT 9999
#define BACKLOG 10
struct head
{
	int i;
	int length;
};

int
main(int argc,char *argv[])
{
	char buf[512] = {0};
	int sockfd,client_fd;
	struct sockaddr_in my_addr;//本机地址
	struct sockaddr_in remote_addr;//客户端地址
	if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
	{
		perror("creat error");
		printf("Create socket error:%s\n", strerror(errno));
		return -1;
	}
	//init
	my_addr.sin_family = AF_INET;
	my_addr.sin_port = htons(SERVPORT);
	my_addr.sin_addr.s_addr = INADDR_ANY;
	bzero(&(my_addr.sin_zero),8);

	if(-1 == bind(sockfd, (struct sockaddr*)&my_addr, sizeof(struct sockaddr)))
	{
		printf("bind error:%s\n",strerror(errno));
		return -1;
	}

	if(-1 == listen(sockfd, BACKLOG))
	{
		printf("listen error:%s\n",strerror(errno));
		return -1;
	}

	int sin_size = sizeof(struct sockaddr_in);
	while(1)
	{
		client_fd = accept(sockfd,(struct sockaddr*)&remote_addr,&sin_size);
		if(-1 == client_fd)
		{
			printf("accept error:%s\n",strerror(errno));
			return -1;
		}
		printf("server:got connection from %s\n", (char*)inet_ntoa(remote_addr.sin_addr));
		struct head hbuf;
		while(1)
		{
			int numbytes = 0;
			memset(buf,0,512);
			memset(&hbuf,0, sizeof(struct head));
			if((recv(client_fd, &buf, sizeof(struct head),0)) <= 0)
			{
				printf("recv error:%s\n",strerror(errno));
				break;
				//return -1;
			}
			memcpy(&hbuf,buf,sizeof(struct head));
			//printf("%d ====== %d :%s\n", hbuf.i, hbuf.length, buf);
			printf("%d ====== %d\n", hbuf.i, hbuf.length);
		}
		close(client_fd);
	}
	return 0;
}
